package com.bs.auth.interceptor;

import com.alibaba.fastjson.JSON;
import com.bs.common.constant.RequestHeaderConstant;
import com.bs.common.vo.LoginUserVo;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author bingshao
 * @date 2022/9/21
 **/
public class AuthRestInterceptor extends HandlerInterceptorAdapter {

    public static final ThreadLocal<LoginUserVo> loginUserThreadLocal = new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userString = request.getHeader(RequestHeaderConstant.USER);
        LoginUserVo loginUserVo = JSON.parseObject(userString, LoginUserVo.class);
        loginUserThreadLocal.set(loginUserVo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        loginUserThreadLocal.remove();
    }
}
